import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 *Description:三个工具类:
 * CountDownLatch:减法计数器
 * CyclicBarrier:加法计数器
 * Semaphore：信号量，限流会用到
 *
 *Version:1.0.0
 *@author shihb
 *@date 2020/5/23 23:37
 */
public class SomeUtils {

  public static void main(String[] args) throws InterruptedException {
//    testCountDownLatch();
    testCyclicBarrier();
//    Semaphore sp = new Semaphore(3);
//    for (int i = 0; i < 6; i++) {
//      new Thread(()->{
//        try {
//          sp.acquire();
//          String name = Thread.currentThread().getName();
//          System.out.println(name+"抢到了车位");
//          TimeUnit.SECONDS.sleep(Integer.parseInt(name));
//          System.out.println(name+"离开了车位");
//
//        } catch (InterruptedException e) {
//          e.printStackTrace();
//        }finally {
//          sp.release();// 释放
//        }
//      },String.valueOf(i+1)).start();
//    }



  }

  private static void testCyclicBarrier() {
    CyclicBarrier cb = new CyclicBarrier(7, () -> {
      //当await的数量到达parties才触发的回调函数
      System.out.println("召唤神龙");
    });
    for (int i = 0; i < 7; i++) {
      final int tmp=i+1;
      new Thread(()->{
        System.out.println("收集了第"+tmp+"龙珠");
        try {
          cb.await();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (BrokenBarrierException e) {
          e.printStackTrace();
        }
      }).start();

    }
  }

  private static void testCountDownLatch() throws InterruptedException {
    CountDownLatch cdl = new CountDownLatch(6);
    for (int i = 0; i < 6; i++) {
      new Thread(()->{
        cdl.countDown();//减一
        System.out.println(Thread.currentThread().getName());
      },String.valueOf(i)).start();
    }
    cdl.await();//阻塞等待CountDownLatch归0
    System.out.println("close");
  }

}
